﻿using Breeze.WebApi;
using RRKAutohaus.Core.EntityFramework;
using RRKAutohaus.Core.Helpers;
using RRKAutohaus.Core.Repositories;
using RRKAutohaus.Model;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace RRKAutohaus.Core
{
    public class UnitOfWork : IUnitOfWork
    {
        public EFContextProvider<RRKAutohausDbContext> DbContext { get; set; }
        protected IRepositoryProvider repositoryProvider { get; set; }

        public IRepository<Image> Image{ get { return GetStandardRepo<Image>(); } }
        public ICarRepository Cars { get { return GetRepo<ICarRepository>(); } }

        

        public UnitOfWork(IRepositoryProvider repositoryProvider)
        {
            DbContext = new EFContextProvider<RRKAutohausDbContext>();
            DbContext.Context .Configuration.LazyLoadingEnabled = false;
            DbContext.Context.Configuration.ProxyCreationEnabled = false;
            DbContext.Context.Configuration.ValidateOnSaveEnabled = false;

            repositoryProvider.dbContext = this.DbContext.Context;
            this.repositoryProvider = repositoryProvider;
        }
        public void Commit()
        {
            DbContext.Context.SaveChanges();
        }

        public void RollBack()
        {
            throw new NotImplementedException();
        }

        private IRepository<T> GetStandardRepo<T>() where T : class
        {
            return repositoryProvider.GetRepositoryForEntityType<T>();
        }

        private T GetRepo<T>() where T : class
        {
            return repositoryProvider.GetRepository<T>();
        }

    }
}
